package com.zhugang.week05;

/**
 * @program algorithms
 * @description: bSearchCycleLessThan
 * @author: chanzhugang
 * @create: 2022/07/04 21:35
 */
public class BSearchCycleMin {

    public static void main(String[] args) {
        BSearchCycleMin bSearchCycleLessThan = new BSearchCycleMin();
        int[] a = new int[]{3, 4, 5, 1, 2};
        int index = bSearchCycleLessThan.bSearchCycleLessThan(a, a.length);
        System.out.println(index);
    }

    /**
     * 循环数组中找最小值（无重复元素）
     * [7,9,10,11,15, 1,3,5,6]
     *
     * @param a
     * @param n
     * @return
     */
    public int bSearchCycleLessThan(int[] a, int n) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = (low + high) / 2;

            if (low == high) {
                return mid;
            }

            if ((mid != 0 && a[mid] < a[mid - 1]) || (mid == 0 && a[mid] < a[high])) {
                return mid;
            } else if (a[mid] > a[high]) {
                // 右循环有序
                low = mid + 1;
            } else {
                // 左侧非循环有序
                high = mid - 1;
            }
        }
        return -1;
    }
}